import React, { useState, useRef, useEffect, useCallback, forwardRef, useImperativeHandle, memo, useMemo } from 'react';
import styles from './index.module.scss';

// 媒体类型配置
const MEDIA_TYPES = {
    VIDEO: 'VIDEO',
    IMAGE: 'IMG'
};

// 支持的媒体元素类型
const SUPPORTED_MEDIA_TYPES = [MEDIA_TYPES.VIDEO, MEDIA_TYPES.IMAGE];

// 媒体元素选择器
const MEDIA_SELECTORS = {
    [MEDIA_TYPES.VIDEO]: 'video',
    [MEDIA_TYPES.IMAGE]: 'img'
};

// 编辑模式配置
const EDIT_MODES = {
    DRAG: 1,      // 拖拽缩放模式
    BRUSH: 2,     // 画笔绘制模式
    ERASER: 3,    // 橡皮擦除模式
    POINT: 4,     // 点选模式
    RECT: 5,      // 框选模式
};

// 控制点配置
const RESIZE_HANDLES = {
    TOP_LEFT: 'tl',
    TOP_RIGHT: 'tr',
    BOTTOM_LEFT: 'bl',
    BOTTOM_RIGHT: 'br',
    TOP: 't',
    BOTTOM: 'b',
    LEFT: 'l',
    RIGHT: 'r'
};

// 控制点大小
const HANDLE_SIZE = 10;

// 控制点样式
const HANDLE_STYLE = {
    backgroundColor: '#fff',
    border: '2px solid #007bff',
    borderRadius: '2px',
    boxShadow: '0 0 4px rgba(0,0,0,0.3)'
};

const CanvasDrawing = forwardRef(({ 
    eraseMode, // 编辑模式：1=拖拽缩放，2=画笔绘制，3=橡皮擦除，4=点选模式，5=框选模式
    toolSize = 12, // 工具大小（画笔/橡皮擦）
    mediaWrapperRef, // 媒体容器引用
    onBrushStrokesChange, // 画笔笔触变化回调
    onEraseStrokesChange, // 擦除笔触变化回调
    onMediaStyleChange, // 媒体样式变化回调
    onPointSelectionChange, // 点选变化回调
    onGreenPointSelectionChange, // 右键点选变化回调
    onRectSelectionChange, // 框选变化回调
    hideDisplayCanvas = false, // 是否隐藏显示Canvas
    selectedSegment = null, // 当前选中的片段
    mediaElementId = null, // 媒体元素的ID
    enableProcessing = true, // 是否启用处理功能
    selectedRatio = null // 选中的画幅比例尺寸
}, ref) => {

    const [mediaScale, setMediaScale] = useState(1);
    const mediaScaleRef = useRef(1);
    const [mediaPosition, setMediaPosition] = useState({ x: 0, y: 0 });
    const [imagePositions, setImagePositions] = useState({
        currentImage: { x: 0, y: 0 },
        copy: { x: 0, y: 0 }
    });
    const [selectedImageKey, setSelectedImageKey] = useState(null); // 选中的图片key
    const [imageSizes, setImageSizes] = useState({}); // 图片尺寸信息
    const [resizeHandle, setResizeHandle] = useState(null); // 当前调整的控制点
    const [resizeStartData, setResizeStartData] = useState(null); // 调整开始时的数据
    const [isScaling, setIsScaling] = useState(false); // 是否正在缩放
    
    // 动态初始化layer图片位置
    useEffect(() => {
        const currentImageDiv = document.getElementById('current-image');
        if (currentImageDiv) {
            const images = currentImageDiv.querySelectorAll('img[data-key^="layer-"]');
            const newPositions = { ...imagePositions };
            let hasNewImages = false;
            
            images.forEach(img => {
                const key = img.getAttribute('data-key');
                if (key && !newPositions[key]) {
                    newPositions[key] = { x: 0, y: 0 };
                    hasNewImages = true;
                }
            });
            
            // 只有当真正有新图片时才更新位置
            if (hasNewImages) {
                setImagePositions(newPositions);
            }
        }
    }, []); // 移除imagePositions依赖，避免无限循环
    
    // 监听DOM变化，初始化新添加的layer图片位置
    useEffect(() => {
        const currentImageDiv = document.getElementById('current-image');
        if (!currentImageDiv) return;
        
        const observer = new MutationObserver(() => {
            const images = currentImageDiv.querySelectorAll('img[data-key^="layer-"]');
            
            // 使用函数式更新，避免闭包问题
            setImagePositions(prevPositions => {
                const newPositions = { ...prevPositions };
                let hasNewImages = false;
                
                images.forEach(img => {
                    const key = img.getAttribute('data-key');
                    if (key && !prevPositions[key]) {
                        newPositions[key] = { x: 0, y: 0 };
                        hasNewImages = true;
                    }
                });
                
                return hasNewImages ? newPositions : prevPositions;
            });
        });
        
        observer.observe(currentImageDiv, {
            childList: true,
            subtree: true
        });
        
        return () => observer.disconnect();
    }, []); // 只在组件挂载时设置观察器
    
    // // 初始化图片尺寸信息
    // useEffect(() => {
    //     const currentImageDiv = document.getElementById('current-image');
    //     if (currentImageDiv) {
    //         const images = currentImageDiv.querySelectorAll('img[data-key^="layer-"]');
            
    //         // 使用函数式更新避免依赖imageSizes
    //         setImageSizes(prevSizes => {
    //             const newSizes = { ...prevSizes };
    //             let hasNewSizes = false;
                
    //             images.forEach(img => {
    //                 const key = img.getAttribute('data-key');
    //                 if (key && !newSizes[key] && img.naturalWidth && img.naturalHeight) {
    //                     newSizes[key] = {
    //                         width: img.naturalWidth,
    //                         height: img.naturalHeight
    //                     };
    //                     hasNewSizes = true;
    //                 }
    //             });
                
    //             return hasNewSizes ? newSizes : prevSizes;
    //         });
    //     }
    // }, []); // 移除imageSizes依赖，避免循环依赖
    
    // 监听图片加载完成，更新尺寸信息
    useEffect(() => {
        const currentImageDiv = document.getElementById('current-image');
        if (!currentImageDiv) return;
        
        const handleImageLoad = (e) => {
            const img = e.target;
            const key = img.getAttribute('data-key');
            if (key && key.startsWith('layer-') && img.width && img.height) {
                setImageSizes(prev => {
                    const newSizes = {
                        ...prev,
                        [key]: {
                            width: img.naturalWidth,
                            height: img.naturalHeight,
                        }
                    };
                    // 图片加载完成后触发样式更新，但需要确保mediaScale已正确设置
                    if (onMediaStyleChange) {
                        // 设置图片加载状态，防止与缩放操作重复触发
                        setIsImageLoading(true);
                        
                        // 使用requestAnimationFrame确保DOM更新后立即触发样式更新
                        requestAnimationFrame(() => {
                            // 总是触发样式更新，让上层组件决定如何处理
                            const mediaStyle = getCurrentMediaStyle();
                            onMediaStyleChange(mediaStyle);
                            setTimeout(()=>{
                                // 无论如何都要触发控制点位置更新
                                setForceUpdateControlPoints(prev => prev + 1);
                            },100)
                            // 立即重置加载状态
                            setIsImageLoading(false);
                        });
                    }
                    
                    return newSizes;
                });
            }
        };
        
        // 使用事件委托监听所有图片的load事件，包括动态添加的图片
        currentImageDiv.addEventListener('load', handleImageLoad, true);
        
        return () => {
            currentImageDiv.removeEventListener('load', handleImageLoad, true);
        };
    }, []);


    
    const [activeImageId, setActiveImageId] = useState(null);
    const [isDragging, setIsDragging] = useState(false);
    const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
    const [isSpacePressed, setIsSpacePressed] = useState(false); // 空格键按下状态
    const [isDrawing, setIsDrawing] = useState(false);
    const [brushStrokes, setBrushStrokes] = useState([]);
    const [currentStroke, setCurrentStroke] = useState([]);
    const [eraseStrokes, setEraseStrokes] = useState([]);
    const [currentEraseStroke, setCurrentEraseStroke] = useState([]);
    const [isErasing, setIsErasing] = useState(false);
    const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
    const [showEraserPreview, setShowEraserPreview] = useState(false);
    const [showBrushPreview, setShowBrushPreview] = useState(false);
    const [prevEraseMode, setPrevEraseMode] = useState(eraseMode); // 记录上一次的工具模式
    const [canvasSize, setCanvasSize] = useState({ width: 0, height: 0 }); // Canvas尺寸状态
    const [selectedPoints, setSelectedPoints] = useState([]); // 点选模式选中的点
    const [greenPoints, setGreenPoints] = useState([]); // 右键点选的绿色点
    const [isSelecting, setIsSelecting] = useState(false); // 是否正在选择
    const [selectionRects, setSelectionRects] = useState([]); // 框选区域数组
    const [currentSelectionRect, setCurrentSelectionRect] = useState(null); // 当前正在绘制的框选区域
    const [isRectSelecting, setIsRectSelecting] = useState(false); // 是否正在框选
    const [rectStart, setRectStart] = useState({ x: 0, y: 0 }); // 框选起始点
    const [needsRedraw, setNeedsRedraw] = useState(false); // 重绘标志
    const [forceUpdateControlPoints, setForceUpdateControlPoints] = useState(0); // 强制更新控制点位置
    
    const canvasRef = useRef(null); // 显示Canvas
    const offscreenCanvasRef = useRef(null); // 离屏Canvas
    const prevCanvasSizeRef = useRef({ width: 0, height: 0 }); // 保存上一次的Canvas尺寸
    // 监听空格键按下和释放
    useEffect(() => {
        const handleKeyDown = (e) => {
            if (e.code === 'Space' && !e.repeat) {
                e.preventDefault();
                setIsSpacePressed(true);
            }
        };

        const handleKeyUp = (e) => {
            if (e.code === 'Space') {
                e.preventDefault();
                setIsSpacePressed(false);
                // 如果正在拖动，停止拖动
                if (isDragging) {
                    setIsDragging(false);
                    setDragStart({ x: 0, y: 0 });
                    setActiveImageId(null);
                    
                    // 清理拖动相关的requestAnimationFrame
                    if (dragThrottleRef.current) {
                        cancelAnimationFrame(dragThrottleRef.current);
                        dragThrottleRef.current = null;
                    }
                }
            }
        };

        document.addEventListener('keydown', handleKeyDown);
        document.addEventListener('keyup', handleKeyUp);

        return () => {
            document.removeEventListener('keydown', handleKeyDown);
            document.removeEventListener('keyup', handleKeyUp);
        };
    }, [isDragging]);


    // 检查元素是否为支持的媒体类型
    const isMediaElement = useCallback((element) => {
        return element && SUPPORTED_MEDIA_TYPES.includes(element.tagName);
    }, []);

    // 获取媒体元素的原始尺寸
    const getMediaDimensions = useCallback((mediaElement) => {
        if (!isMediaElement(mediaElement)) {
            return null;
        }

        const isVideo = mediaElement.tagName === MEDIA_TYPES.VIDEO;
        const isImage = mediaElement.tagName === MEDIA_TYPES.IMAGE;

        if (isVideo) {
            const { videoWidth, videoHeight } = mediaElement;
            if (!videoWidth || !videoHeight || videoWidth === 0 || videoHeight === 0) {
                return null;
            }
            return { width: videoWidth, height: videoHeight };
        }

        if (isImage) {
            const { naturalWidth, naturalHeight } = mediaElement;
            if (!naturalWidth || !naturalHeight || naturalWidth === 0 || naturalHeight === 0) {
                return null;
            }
            return { width: naturalWidth, height: naturalHeight };
        }

        return null;
    }, [isMediaElement]);

    // 获取媒体元素的通用函数
    const getMediaElement = useCallback(() => {
        if (!enableProcessing) return null;
        
        const wrapper = mediaWrapperRef.current;
        if (!wrapper) return null;
        
        // 优先使用ID获取元素
        if (mediaElementId) {
            const element = document.getElementById(mediaElementId);
            if (isMediaElement(element)) {
                return element;
            }
        }
        
        // 回退到querySelector方式
        const selectors = Object.values(MEDIA_SELECTORS).join(', ');
        return wrapper.querySelector(selectors);
    }, [mediaElementId, isMediaElement, enableProcessing]);

    // 暴露方法给父组件
    useImperativeHandle(ref, () => ({
        getCanvasImage,
        clearBrushStrokes,
        getMediaStyle,
        handleDownloadResizedImage,
        setSelectedImage: (imageKey) => {
            setSelectedImageKey(imageKey);
        }
    }), [mediaScale, mediaPosition, enableProcessing, isDragging, selectedRatio]);

    // 防止重复调用onMediaStyleChange的状态
    const [isImageLoading, setIsImageLoading] = useState(false);
    const onMediaStyleChangeTimeoutRef = useRef(null);
    
    // 当媒体缩放或位置改变时，通知父组件更新媒体样式
    useEffect(() => {
        if (onMediaStyleChange && !isImageLoading) {
            // 清除之前的定时器，防止重复调用
            if (onMediaStyleChangeTimeoutRef.current) {
                clearTimeout(onMediaStyleChangeTimeoutRef.current);
            }
            
            // 使用防抖机制，避免频繁调用
            onMediaStyleChangeTimeoutRef.current = setTimeout(() => {
                const mediaStyle = getCurrentMediaStyle();
                onMediaStyleChange(mediaStyle);
                onMediaStyleChangeTimeoutRef.current = null;
            }, 0); // 移除延时，立即更新
        }
    }, [mediaScale, mediaPosition, enableProcessing, isDragging, onMediaStyleChange, selectedRatio, imagePositions, isImageLoading]);

    // 处理鼠标滚轮缩放
    const handleWheel = (e) => {
        if (!enableProcessing) return;
        e.preventDefault();
        
        // 设置缩放状态
        setIsScaling(true);
        
        const delta = e.deltaY > 0 ? -0.1 : 0.1;
        const newScale = Math.max(0.1, Math.min(5, mediaScale + delta));
        
        // 如果缩放到1，重置位置
        if (newScale <= 1) {
            setMediaScale(newScale);
            mediaScaleRef.current = newScale;
            setMediaPosition({ x: 0, y: 0 });
            // selectedRatio模式下保持图片位置，普通模式下重置位置
            if (!selectedRatio) {
                const currentImageDiv = document.getElementById('current-image');
                if (currentImageDiv) {
                    const images = currentImageDiv.querySelectorAll('img[data-key^="layer-"]');
                    if(images.length>0){
                        setImagePositions(prev => {
                            const newPositions = { ...prev };
                            let hasNewImages = false;
                            images.forEach(img => {
                                const key = img.getAttribute('data-key');
                                if (key && prev[key]) {
                                    newPositions[key] = { x: 0, y: 0 };
                                    hasNewImages = true;
                                }
                            });
                            
                            return hasNewImages ? newPositions : prev;
                        });
                    }else{
                        setImagePositions({
                            currentImage: { x: 0, y: 0 },
                            copy: { x: 0, y: 0 }
                        });
                    }
                }
            }
            
            // 延迟重置缩放状态，确保缩放结束后再显示控制点
            setTimeout(() => {
                // 使用requestAnimationFrame确保DOM完全更新后再显示控制点
                requestAnimationFrame(() => {
                    setIsScaling(false);
                });
            }, 200);
            return;
        }
        
        // 以鼠标位置为中心进行缩放
        const wrapper = mediaWrapperRef.current;
        if (wrapper && newScale !== mediaScale) {
            const rect = wrapper.getBoundingClientRect();
            // 计算鼠标相对于容器中心的位置
            const mouseX = e.clientX - rect.left - rect.width / 2;
            const mouseY = e.clientY - rect.top - rect.height / 2;
            
            // 计算缩放比例变化
            const scaleChange = newScale / mediaScale;
            
            // 调整媒体位置，使鼠标位置保持不变
            const newX = mediaPosition.x - (mouseX / mediaScale) * (scaleChange - 1);
            const newY = mediaPosition.y - (mouseY / mediaScale) * (scaleChange - 1);
            setMediaScale(newScale);
            mediaScaleRef.current = newScale;
            setMediaPosition({ x: newX, y: newY });
        }
        
        // 延迟重置缩放状态，确保缩放结束后再显示控制点
        setTimeout(() => {
            // 使用requestAnimationFrame确保DOM完全更新后再显示控制点
            requestAnimationFrame(() => {
                setIsScaling(false);
            });
        }, 200);
    };



    // 添加非passive的wheel事件监听器
    useEffect(() => {
        const wrapper = mediaWrapperRef.current;
        if (!wrapper) return;

        const wheelHandler = (e) => {
            if (enableProcessing) {
                handleWheel(e);
            }
        };

        wrapper.addEventListener('wheel', wheelHandler, { passive: false });
        
        return () => {
            wrapper.removeEventListener('wheel', wheelHandler);
        };
    }, [enableProcessing, mediaScale, mediaPosition, handleWheel]);

    // 检测点击的是哪个图片
    const detectClickedImage = (e) => {
        const currentImageDiv = document.getElementById('current-image');
        if (!currentImageDiv) return null;
        
        const images = currentImageDiv.querySelectorAll('img');
        const clickX = e.clientX;
        const clickY = e.clientY;
        
        for (let i = images.length - 1; i >= 0; i--) {
            const img = images[i];
            const rect = img.getBoundingClientRect();
            if (clickX >= rect.left && clickX <= rect.right && 
                clickY >= rect.top && clickY <= rect.bottom) {
                // 检查是否是layer模式的图片
                const key = img.getAttribute('data-key');
                if (key && key.startsWith('layer-')) {
                    return key;
                }
                
                // 兼容原有逻辑
                if (img.src.includes('copy') || img.alt === '') {
                    return 'copy';
                } else {
                    return 'currentImage';
                }
            }
        }
        return null;
    };

    // 处理鼠标按下开始拖动
    const handleMouseDown = (e) => {
        // 空格键拖动：拖动整个画布
        if (isSpacePressed) {
            // 只有缩放大于1时才允许拖动整个画布
            if (mediaScale <= 1) return;
            e.preventDefault();
            
            setIsDragging(true);
            setDragStart({
                x: e.clientX,
                y: e.clientY,
                startX: mediaPosition.x,
                startY: mediaPosition.y
            });
            return;
        }
        
        // DRAG模式：拖动画布内的元素
        if (eraseMode !== EDIT_MODES.DRAG) return;
        
        // 检测是否为多图片模式（DOM中存在多个图片）
        const imageElements = mediaWrapperRef?.current?.querySelectorAll('img') || [];
        const isMultiImageMode = imageElements.length > 1;
        
        // selectedRatio模式下始终允许拖动，多图片模式下也允许拖动，否则需要按空格键且缩放大于1
        if (!selectedRatio && !isMultiImageMode && (!isSpacePressed || mediaScale <= 1)) return;
        e.preventDefault();
        
        // 检测点击的是哪个图片
        const clickedImageId = detectClickedImage(e);
        if (selectedRatio&&(!clickedImageId||selectedImageKey!=clickedImageId)) return;
        
        // 确定要拖动的图片ID
        let targetImageId = selectedImageKey||clickedImageId;
        
        setActiveImageId(targetImageId);
        setIsDragging(true);
        
        // 根据模式选择正确的位置状态
        let currentPos;
        if (selectedRatio) {
            currentPos = imagePositions[targetImageId] || { x: 0, y: 0 };
        } else {
            currentPos = mediaPosition;
        }
        
        setDragStart({
            x: e.clientX,
            y: e.clientY,
            startX: currentPos.x,
            startY: currentPos.y
        });
    };

    // 拖动节流控制
    const dragThrottleRef = useRef(null);
    const lastDragTimeRef = useRef(0);
    
    // 处理鼠标移动拖动
    const handleMouseMove = useCallback((e) => {
        if (!isDragging) return;
        // 空格键拖动：拖动整个画布
        if (isSpacePressed) {
            if (mediaScale <= 1) return;
            e.preventDefault();
            
            const deltaX = e.clientX - dragStart.x;
            const deltaY = e.clientY - dragStart.y;
            
            // 只有移动距离超过阈值时才更新位置
            if (Math.abs(deltaX) < 2 && Math.abs(deltaY) < 2) return;
            
            const newX = Math.round(dragStart.startX + deltaX / mediaScale);
            const newY = Math.round(dragStart.startY + deltaY / mediaScale);
            
            // 拖动边界处理
            const wrapper = mediaWrapperRef.current;
            if (!wrapper) return;
            
            const wrapperRect = wrapper.getBoundingClientRect();
            const scaledMediaWidth = wrapperRect.width * mediaScale;
            const scaledMediaHeight = wrapperRect.height * mediaScale;

            const overflowX = Math.max(0, scaledMediaWidth - wrapperRect.width);
            const overflowY = Math.max(0, scaledMediaHeight - wrapperRect.height);
            
            const maxDragX = overflowX / 2 / mediaScale;
            const maxDragY = overflowY / 2 / mediaScale;
            
            const clampedX = Math.round(Math.max(-maxDragX, Math.min(maxDragX, newX)));
            const clampedY = Math.round(Math.max(-maxDragY, Math.min(maxDragY, newY)));
            
            setMediaPosition({ x: clampedX, y: clampedY });
            return;
        }
        
        // DRAG模式：拖动画布内的元素
        if (!activeImageId || eraseMode !== EDIT_MODES.DRAG) return;
        
        // 节流控制，限制更新频率为60fps
        const now = performance.now();
        if (now - lastDragTimeRef.current < 16) return; // 约60fps
        lastDragTimeRef.current = now;
        
        // 检测是否为多图片模式（缓存结果）
        const imageElements = mediaWrapperRef?.current?.querySelectorAll('img') || [];
        const isMultiImageMode = imageElements.length > 1;
        
        // selectedRatio模式下始终允许拖动，多图片模式下也允许拖动，否则需要按空格键且缩放大于1
        if (!selectedRatio && !isMultiImageMode && (!isSpacePressed || mediaScale <= 1)) return;
        e.preventDefault();
        
        const deltaX = e.clientX - dragStart.x;
        const deltaY = e.clientY - dragStart.y;
        
        // 只有移动距离超过阈值时才更新位置（提高阈值减少计算）
        if (Math.abs(deltaX) < 2 && Math.abs(deltaY) < 2) return;
        
        // 根据模式选择正确的缩放计算
        let newX, newY;
        newX = Math.round(dragStart.startX + deltaX / mediaScale);
        newY = Math.round(dragStart.startY + deltaY / mediaScale);
        // 拖动边界处理（优化性能）
        const wrapper = mediaWrapperRef.current;
        if (!wrapper) return;
        
        // selectedRatio模式下的拖动逻辑
        if (selectedRatio) {
            // 获取当前选中图片的实际尺寸（缓存DOM查询）
            const mediaContainer = document.getElementById(mediaElementId);
            if (mediaContainer && activeImageId) {
                const currentImage = mediaContainer.querySelector(`img[data-key="${activeImageId}"]`);
                if (currentImage && currentImage.naturalWidth && currentImage.naturalHeight) {
                    // 获取selectedRatio模式下的显示信息
                    const displayInfo = calculateSelectedRatioDisplayInfo();
                    const { displayWidth, displayHeight } = displayInfo;
                    
                    // 简化边界计算
                    const maxOffsetX = (displayWidth - currentImage.width) / 2;
                    const maxOffsetY = (displayHeight - currentImage.height) / 2;
                    
                    // 简化边界限制，移除吸附逻辑以提升性能
                    const clampedX = Math.round(Math.max(-maxOffsetX, Math.min(maxOffsetX, newX)));
                    const clampedY = Math.round(Math.max(-maxOffsetY, Math.min(maxOffsetY, newY)));
                    
                    // 使用requestAnimationFrame优化渲染
                    if (dragThrottleRef.current) {
                        cancelAnimationFrame(dragThrottleRef.current);
                    }
                    dragThrottleRef.current = requestAnimationFrame(() => {
                        setImagePositions(prev => ({
                            ...prev,
                            [activeImageId]: { x: clampedX, y: clampedY }
                        }));
                    });
                }
            }
        } else {
            // 原有的拖动逻辑（优化性能）
            const wrapperRect = wrapper.getBoundingClientRect();
            const scaledMediaWidth = wrapperRect.width * mediaScale;
            const scaledMediaHeight = wrapperRect.height * mediaScale;

            const overflowX = Math.max(0, scaledMediaWidth - wrapperRect.width);
            const overflowY = Math.max(0, scaledMediaHeight - wrapperRect.height);
            
            const maxDragX = overflowX / 2 / mediaScale;
            const maxDragY = overflowY / 2 / mediaScale;
            
            // 简化边界限制，移除吸附逻辑以提升性能
            const clampedX = Math.round(Math.max(-maxDragX, Math.min(maxDragX, newX)));
            const clampedY = Math.round(Math.max(-maxDragY, Math.min(maxDragY, newY)));
            
            // 使用requestAnimationFrame优化渲染
            if (dragThrottleRef.current) {
                cancelAnimationFrame(dragThrottleRef.current);
            }
            dragThrottleRef.current = requestAnimationFrame(() => {
                setMediaPosition({ x: clampedX, y: clampedY });
            });
        }
    }, [isDragging, mediaScale, dragStart, selectedRatio, activeImageId, isSpacePressed]);

    // 处理鼠标抬起结束拖动
    const handleMouseUp = () => {
        setIsDragging(false);
        setDragStart({ x: 0, y: 0 });
        setActiveImageId(null);
        
        // 清理拖动相关的requestAnimationFrame
        if (dragThrottleRef.current) {
            cancelAnimationFrame(dragThrottleRef.current);
            dragThrottleRef.current = null;
        }
        
        if (isDrawing) {
            setIsDrawing(false);
            if (currentStroke.length > 0) {

                const newBrushStrokes = [...brushStrokes, { stroke: currentStroke, timestamp: Date.now(), toolSize }];
                setBrushStrokes(newBrushStrokes);
                onBrushStrokesChange?.(newBrushStrokes);
                setCurrentStroke([]);
                // Canvas模式下重绘
                setTimeout(() => redrawCanvas(), 0);
            }
        }
        
        if (isErasing) {
            if (eraseMode === EDIT_MODES.ERASER) {
                // 橡皮擦模式：透明擦除
                handleEraseEnd(); // 调用擦除结束处理
            }
        }
        
        // 点选模式处理
        if (isSelecting && eraseMode === EDIT_MODES.POINT) {
            setIsSelecting(false);
        }
        
        // 框选模式处理
        if (isRectSelecting && eraseMode === EDIT_MODES.RECT) {
            setIsRectSelecting(false);
            // 将当前框选添加到框选数组中
            if (currentSelectionRect && currentSelectionRect.width > 0 && currentSelectionRect.height > 0) {
                // 将显示坐标转换为原图坐标
                const displayInfo = getCurrentDisplayInfo();
                const mediaElement = getMediaElement();
                const originalImageInfo = getMediaDimensions(mediaElement);
                
                if (displayInfo && originalImageInfo) {
                    const scaleX = originalImageInfo.width / displayInfo.displayWidth;
                    const scaleY = originalImageInfo.height / displayInfo.displayHeight;
                    
                    // 转换为原图坐标的tlx、tly、brx、bry格式
                    const rectData = {
                        tlx: currentSelectionRect.x * scaleX,
                        tly: currentSelectionRect.y * scaleY,
                        brx: (currentSelectionRect.x + currentSelectionRect.width) * scaleX,
                        bry: (currentSelectionRect.y + currentSelectionRect.height) * scaleY
                    };
                    const newSelectionRects = [...selectionRects, rectData];
                    setSelectionRects(newSelectionRects);
                    
                    // 调用框选变化回调
                    onRectSelectionChange?.(newSelectionRects);
                }
            }
            setCurrentSelectionRect(null);
        }
    };

    // 坐标缩放函数
    const scaleCoordinates = (oldSize, newSize, strokes) => {
        if (oldSize.width === 0 || oldSize.height === 0) return strokes;
        
        const scaleX = newSize.width / oldSize.width;
        const scaleY = newSize.height / oldSize.height;
        
        return strokes.map(strokeData => ({
            ...strokeData,
            stroke: strokeData.stroke.map(point => ({
                x: point.x * scaleX,
                y: point.y * scaleY
            })),
            toolSize: strokeData.toolSize // 保持原有的toolSize
        }));
    };

    // 通用坐标计算函数
    const calculateDrawingCoordinates = (e) => {
        const displayInfo = getCurrentDisplayInfo();
        if (!displayInfo) return null;
        
        const { displayWidth, displayHeight, offsetX, offsetY, wrapperRect } = displayInfo;
        const mediaX = e.clientX - wrapperRect.left - offsetX;
        const mediaY = e.clientY - wrapperRect.top - offsetY;
        
        const mediaCenterX = displayWidth / 2;
        const mediaCenterY = displayHeight / 2;
        const rawX = mediaX - mediaCenterX;
        const rawY = mediaY - mediaCenterY;
        
        // selectedRatio模式下需要考虑拖动偏移量
        if (selectedRatio) {
            return {
                x: (rawX / mediaScale - mediaPosition.x) + mediaCenterX,
                y: (rawY / mediaScale - mediaPosition.y) + mediaCenterY
            };
        } else {
            // 原有逻辑
            return {
                x: (rawX / mediaScale - mediaPosition.x) + mediaCenterX,
                y: (rawY / mediaScale - mediaPosition.y) + mediaCenterY
            };
        }
    };

    // 处理画笔绘制开始
    const handleBrushStart = (e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.BRUSH) return;
        e.preventDefault();
        setIsDrawing(true);
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            setCurrentStroke([coords]);
        }
    };

    // 处理画笔绘制过程
    const handleBrushMove = useCallback((e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.BRUSH) return;
        e.preventDefault();
        
        // 节流更新鼠标位置用于显示画笔预览
        const wrapper = mediaWrapperRef.current;
        if (wrapper) {
            const rect = wrapper.getBoundingClientRect();
            const newPos = {
                x: e.clientX - rect.left,
                y: e.clientY - rect.top
            };
            // 减少鼠标位置更新频率
            setMousePosition(prev => {
                if (!prev || Math.abs(prev.x - newPos.x) > 5 || Math.abs(prev.y - newPos.y) > 5) {
                    return newPos;
                }
                return prev;
            });
        }
        
        if (!isDrawing) return;
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            setCurrentStroke(prev => {
                // 避免重复添加相同坐标点
                const lastPoint = prev[prev.length - 1];
                if (lastPoint && Math.abs(lastPoint.x - coords.x) < 1 && Math.abs(lastPoint.y - coords.y) < 1) {
                    return prev;
                }
                return [...prev, coords];
            });
        }
    }, [enableProcessing, eraseMode, isDrawing]);

    // 清除所有画笔痕迹
    const clearBrushStrokes = () => {
        setBrushStrokes([]);
        setCurrentStroke([]);
        setEraseStrokes([]);
        setCurrentEraseStroke([]);
        // 清除点选和框选状态
        setSelectedPoints([]);
        setGreenPoints([]);
        setSelectionRects([]);
        setCurrentSelectionRect(null);
        
        // 通知父组件状态变化
        onBrushStrokesChange?.([]);
        onEraseStrokesChange?.([]);
        onPointSelectionChange?.([]);
        onRectSelectionChange?.([]);
        
        // 立即清除Canvas内容（双Canvas架构）
        setTimeout(() => {
            // 清除离屏Canvas
            const offscreenCtx = getCanvasContext();
            if (offscreenCtx) {
                const offscreenCanvas = offscreenCanvasRef.current;
                offscreenCtx.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
            }
            
            // 清除显示Canvas
            const displayCtx = getDisplayCanvasContext();
            if (displayCtx) {
                const displayCanvas = canvasRef.current;
                displayCtx.clearRect(0, 0, displayCanvas.width, displayCanvas.height);
            }
        }, 0);
    };

    // 处理橡皮擦除开始
    const handleEraseStart = (e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.ERASER) return;
        e.preventDefault();
        setIsErasing(true);
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            setCurrentEraseStroke([coords]);
        }
    };

    // 处理橡皮擦除过程
    const handleEraseMove = useCallback((e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.ERASER) return;
        e.preventDefault();
        
        // 更新鼠标位置用于显示橡皮擦预览
        const wrapper = mediaWrapperRef.current;
        if (wrapper) {
            const rect = wrapper.getBoundingClientRect();
            setMousePosition({
                x: e.clientX - rect.left,
                y: e.clientY - rect.top
            });
        }
        
        if (!isErasing) return;
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            setCurrentEraseStroke(prev => {
                // 避免重复添加相同坐标点
                const lastPoint = prev[prev.length - 1];
                if (lastPoint && Math.abs(lastPoint.x - coords.x) < 1 && Math.abs(lastPoint.y - coords.y) < 1) {
                    return prev;
                }
                return [...prev, coords];
            });
        }
    }, [enableProcessing, eraseMode, isErasing]);

    // 处理橡皮擦除结束
    const handleEraseEnd = () => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.ERASER || !isErasing) return;
        setIsErasing(false);
        if (currentEraseStroke.length > 0) {

            const newEraseStrokes = [...eraseStrokes, { stroke: currentEraseStroke, timestamp: Date.now(), toolSize }];
            setEraseStrokes(newEraseStrokes);
            onEraseStrokesChange?.(newEraseStrokes);
            setCurrentEraseStroke([]);
            // Canvas模式下重绘
            setTimeout(() => redrawCanvas(), 0);
        }
    };

    // 处理点选模式开始（左键）
    const handlePointStart = (e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.POINT) return;
        // 只允许左键点击
        if (e.button !== 0) return;
        e.preventDefault();
        setIsSelecting(true);
        
        // 检查点击是否在媒体显示区域内
        const displayInfo = getCurrentDisplayInfo();
        if (!displayInfo) return;
        
        const { displayWidth, displayHeight, offsetX, offsetY, wrapperRect } = displayInfo;
        const clickX = e.clientX - wrapperRect.left;
        const clickY = e.clientY - wrapperRect.top;
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            // 检查计算后的坐标是否在有效范围内（考虑缩放和位移）
            if (coords.x < 0 || coords.x > displayWidth || coords.y < 0 || coords.y > displayHeight) {
                return; // 坐标超出媒体区域，不触发点选
            }
            // 计算原图坐标（在点击时就确定，后续不再变化）
            const mediaElement = getMediaElement();
            const originalImageInfo = getMediaDimensions(mediaElement);
            if (!originalImageInfo) {
                return;
            }
            const displayInfo = getCurrentDisplayInfo();
            let originalCoords = { x: coords.x, y: coords.y };
            
            if (originalImageInfo && displayInfo) {
                const scaleX = originalImageInfo.width / displayInfo.displayWidth;
                const scaleY = originalImageInfo.height / displayInfo.displayHeight;
                
                originalCoords = {
                    x: coords.x * scaleX,
                    y: coords.y * scaleY
                };
            }
            
            // 存储包含显示坐标和原图坐标的点对象
            const newPoint = {
                displayX: coords.x,
                displayY: coords.y,
                originalX: originalCoords.x,
                originalY: originalCoords.y
            };
            const newSelectedPoints = [...selectedPoints, newPoint];
            setSelectedPoints(newSelectedPoints);
            
            // 传递给父组件的原图坐标（从存储的原图坐标中提取）
            const originalSelectedPoints = newSelectedPoints.map(point => ({
                x: point.originalX,
                y: point.originalY
            }));
            onPointSelectionChange?.(originalSelectedPoints);
        }
    };

    // 处理点选模式开始（右键 - 绿色点）
    const handleGreenPointStart = (e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.POINT) return;
        e.preventDefault();
        
        // 检查点击是否在媒体显示区域内
        const displayInfo = getCurrentDisplayInfo();
        if (!displayInfo) return;
        
        const { displayWidth, displayHeight, offsetX, offsetY, wrapperRect } = displayInfo;
        const clickX = e.clientX - wrapperRect.left;
        const clickY = e.clientY - wrapperRect.top;
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            // 检查计算后的坐标是否在有效范围内（考虑缩放和位移）
            if (coords.x < 0 || coords.x > displayWidth || coords.y < 0 || coords.y > displayHeight) {
                return; // 坐标超出媒体区域，不触发点选
            }
            // 计算原图坐标（在点击时就确定，后续不再变化）
            const mediaElement = getMediaElement();
            const originalImageInfo = getMediaDimensions(mediaElement);
            if (!originalImageInfo) {
                return;
            }
            const displayInfo = getCurrentDisplayInfo();
            let originalCoords = { x: coords.x, y: coords.y };
            
            if (originalImageInfo && displayInfo) {
                const scaleX = originalImageInfo.width / displayInfo.displayWidth;
                const scaleY = originalImageInfo.height / displayInfo.displayHeight;
                
                originalCoords = {
                    x: coords.x * scaleX,
                    y: coords.y * scaleY
                };
            }
            
            // 存储包含显示坐标和原图坐标的绿色点对象
            const newGreenPoint = {
                displayX: coords.x,
                displayY: coords.y,
                originalX: originalCoords.x,
                originalY: originalCoords.y
            };
            const newGreenPoints = [...greenPoints, newGreenPoint];
            setGreenPoints(newGreenPoints);
            
            // 调用绿色点变化回调，传递原图坐标
            if (onGreenPointSelectionChange) {
                const originalCoords = newGreenPoints.map(point => ({
                    x: point.originalX,
                    y: point.originalY
                }));
                onGreenPointSelectionChange(originalCoords);
            }
        }
    };

    // 处理框选模式开始
    const handleRectStart = (e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.RECT) return;
        e.preventDefault();
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            // 获取媒体显示区域信息进行边界限制
            const displayInfo = getCurrentDisplayInfo();
            if (!displayInfo) return;
            
            const { displayWidth, displayHeight } = displayInfo;
            
            // 限制框选起始坐标在媒体显示区域内
            const clampedCoords = {
                x: Math.max(0, Math.min(coords.x, displayWidth)),
                y: Math.max(0, Math.min(coords.y, displayHeight))
            };
            
            setIsRectSelecting(true);
            setRectStart({ x: clampedCoords.x, y: clampedCoords.y });
            setCurrentSelectionRect({ x: clampedCoords.x, y: clampedCoords.y, width: 0, height: 0 });
        }
    };

    // 处理框选模式移动
    const handleRectMove = useCallback((e) => {
        if (!enableProcessing || eraseMode !== EDIT_MODES.RECT || !isRectSelecting) return;
        e.preventDefault();
        
        const coords = calculateDrawingCoordinates(e);
        if (coords) {
            // 获取媒体显示区域信息进行边界限制
            const displayInfo = getCurrentDisplayInfo();
            if (!displayInfo) return;
            
            const { displayWidth, displayHeight } = displayInfo;
            
            // 限制框选起始坐标在媒体显示区域内
            const clampedCoords = {
                x: Math.max(0, Math.min(coords.x, displayWidth)),
                y: Math.max(0, Math.min(coords.y, displayHeight))
            };
            
            const width = clampedCoords.x - rectStart.x;
            const height = clampedCoords.y - rectStart.y;
            
            let newRect = {
                x: width < 0 ? clampedCoords.x : rectStart.x,
                y: height < 0 ? clampedCoords.y : rectStart.y,
                width: Math.abs(width),
                height: Math.abs(height)
            };
            
            // 确保框选矩形完全在媒体显示区域内
            newRect = {
                x: Math.max(0, Math.min(newRect.x, displayWidth - newRect.width)),
                y: Math.max(0, Math.min(newRect.y, displayHeight - newRect.height)),
                width: Math.min(newRect.width, displayWidth),
                height: Math.min(newRect.height, displayHeight)
            };
            
            // 只有当矩形尺寸变化超过阈值时才更新
            setCurrentSelectionRect(prev => {
                if (!prev || 
                    Math.abs(prev.width - newRect.width) > 2 || 
                    Math.abs(prev.height - newRect.height) > 2 ||
                    Math.abs(prev.x - newRect.x) > 2 ||
                    Math.abs(prev.y - newRect.y) > 2) {
                    return newRect;
                }
                return prev;
            });
        }
    }, [enableProcessing, eraseMode, isRectSelecting, rectStart]);

    // 计算媒体显示信息的辅助函数
    const calculateMediaDisplayInfo = () => {
        const wrapper = mediaWrapperRef.current;
        if (!wrapper) return null;
        
        // 使用通用函数获取媒体元素
        let mediaElement = getMediaElement();
        if (!mediaElement) return null;
        
        // 检查媒体元素是否已加载并获取尺寸
        const mediaDimensions = getMediaDimensions(mediaElement);
        if (!mediaDimensions) {
            return null;
        }
        
        const { width: mediaWidth, height: mediaHeight } = mediaDimensions;
        
        const wrapperRect = wrapper.getBoundingClientRect();
        const mediaAspectRatio = mediaWidth / mediaHeight;
        const containerAspectRatio = (wrapperRect.width) / (wrapperRect.height);
        
        // 检查计算结果是否有效
        if (!isFinite(mediaAspectRatio) || !isFinite(containerAspectRatio)) {
            return null;
        }
        
        let displayWidth, displayHeight, offsetX, offsetY;
        if (mediaAspectRatio > containerAspectRatio) {
            displayWidth = wrapperRect.width;
            displayHeight = displayWidth / mediaAspectRatio;
            offsetX = 0;
            offsetY = (wrapperRect.height- displayHeight) / 2;
        } else {
            displayWidth = (wrapperRect.height) * mediaAspectRatio;
            displayHeight = wrapperRect.height;
            offsetX = (wrapperRect.width- displayWidth) / 2;
            offsetY = 0;
        }
        return { displayWidth, displayHeight, offsetX, offsetY, wrapperRect };
    };

    // selectedRatio模式专用的显示信息计算函数
    const calculateSelectedRatioDisplayInfo = () => {
        if (!selectedRatio) return null;
        
        const wrapper = mediaWrapperRef.current;
        if (!wrapper) return null;
        
        const wrapperRect = wrapper.getBoundingClientRect();
        
        // selectedRatio模式：根据设置的宽高比在容器内缩放
        // 确保9:16这样的比例正确处理：宽度小于高度
        const targetAspectRatio = selectedRatio.width / selectedRatio.height;
        const containerAspectRatio = wrapperRect.width / wrapperRect.height;
        
        let displayWidth, displayHeight, offsetX, offsetY;
        
        // 比较目标宽高比和容器宽高比
        if (targetAspectRatio > containerAspectRatio) {
            // 目标比例更宽（如16:9），以容器宽度为准
            displayWidth = wrapperRect.width;
            displayHeight = displayWidth / targetAspectRatio;
            offsetX = 0;
            offsetY = (wrapperRect.height - displayHeight) / 2;
        } else {
            // 目标比例更高（如9:16），以容器高度为准
            displayHeight = wrapperRect.height;
            displayWidth = displayHeight * targetAspectRatio;
            offsetX = (wrapperRect.width - displayWidth) / 2;
            offsetY = 0;
        }
        
        return { displayWidth, displayHeight, offsetX, offsetY, wrapperRect };
    };

    // 获取当前模式下的显示信息
    const getCurrentDisplayInfo = () => {
        return selectedRatio ? calculateSelectedRatioDisplayInfo() : calculateMediaDisplayInfo();
    };

    // Canvas绘制相关函数
    const getCanvasContext = () => {
        const canvas = offscreenCanvasRef.current; // 使用离屏Canvas进行绘制
        if (!canvas) return null;
        return canvas.getContext('2d');
    };
    
    // 获取显示Canvas上下文
    const getDisplayCanvasContext = () => {
        const canvas = canvasRef.current;
        if (!canvas) return null;
        return canvas.getContext('2d');
    };

    // 重绘Canvas（双Canvas架构）
    const redrawCanvas = useCallback(() => {
        const offscreenCtx = getCanvasContext();
        const displayCtx = getDisplayCanvasContext();
        if (!offscreenCtx || !displayCtx) return;
        
        const offscreenCanvas = offscreenCanvasRef.current;
        const displayCanvas = canvasRef.current;
        // 使用通用函数获取媒体元素
        let mediaElement = getMediaElement();
        if (!mediaElement) return;
        
        // 清除离屏Canvas
        offscreenCtx.clearRect(0, 0, offscreenCanvas.width, offscreenCanvas.height);
        
        // 创建所有操作的时间序列数组
        const allOperations = [];
        
        // 添加画笔笔画（带时间戳）- 只显示在当前片段时间范围内的轨迹
        brushStrokes.forEach(strokeData => {
            const strokeTimestamp = strokeData.timestamp || 0;
            
            // 检查轨迹是否在当前选中片段的时间范围内
            let shouldShow = true;
            if (selectedSegment && selectedSegment.startTime !== undefined && selectedSegment.endTime !== undefined) {
                const startTime = typeof selectedSegment.startTime === 'string' ? 
                    parseFloat(selectedSegment.startTime.split(':').reduce((acc, time) => (60 * acc) + +time)) :
                    selectedSegment.startTime;
                const endTime = typeof selectedSegment.endTime === 'string' ? 
                    parseFloat(selectedSegment.endTime.split(':').reduce((acc, time) => (60 * acc) + +time)) :
                    selectedSegment.endTime;
                
                shouldShow = video.currentTime >= startTime && video.currentTime <= endTime; // Convert ms to seconds
            }
            
            if (shouldShow) {
                allOperations.push({
                    type: 'brush',
                    stroke: strokeData.stroke || strokeData, // 兼容旧格式
                    timestamp: strokeTimestamp,
                    toolSize: strokeData.toolSize || toolSize // 使用保存的toolSize，如果没有则使用当前值
                });
            }
        });
        
        // 添加橡皮擦笔画（带时间戳）- 只显示在当前片段时间范围内的轨迹
        eraseStrokes.forEach(strokeData => {
            const strokeTimestamp = strokeData.timestamp || 0;
            
            // 检查轨迹是否在当前选中片段的时间范围内
            let shouldShow = true;
            if (selectedSegment && selectedSegment.startTime !== undefined && selectedSegment.endTime !== undefined) {
                const startTime = typeof selectedSegment.startTime === 'string' ? 
                    parseFloat(selectedSegment.startTime.split(':').reduce((acc, time) => (60 * acc) + +time)) :
                    selectedSegment.startTime;
                const endTime = typeof selectedSegment.endTime === 'string' ? 
                    parseFloat(selectedSegment.endTime.split(':').reduce((acc, time) => (60 * acc) + +time)) :
                    selectedSegment.endTime;
                
                shouldShow = video.currentTime >= startTime && video.currentTime <= endTime; // Convert ms to seconds
            }
            
            if (shouldShow) {
                allOperations.push({
                    type: 'eraser',
                    stroke: strokeData.stroke || strokeData, // 兼容旧格式
                    timestamp: strokeTimestamp,
                    toolSize: strokeData.toolSize || toolSize // 使用保存的toolSize，如果没有则使用当前值
                });
            }
        });
        
        // 按时间戳排序，确保操作按正确顺序执行
        allOperations.sort((a, b) => a.timestamp - b.timestamp);
        
        // 在离屏Canvas上按顺序执行所有操作
        allOperations.forEach(operation => {
            drawStroke(offscreenCtx, operation.stroke, operation.type, operation.toolSize);
        });
        
        // 在离屏Canvas上绘制当前笔画
        if (currentStroke.length > 0) {
            drawStroke(offscreenCtx, currentStroke, 'brush', toolSize);
        }
        
        // 在离屏Canvas上绘制当前橡皮擦笔画
        if (currentEraseStroke.length > 0) {
            drawStroke(offscreenCtx, currentEraseStroke, 'eraser', toolSize);
        }
        
        // 将离屏Canvas内容复制到显示Canvas
        displayCtx.clearRect(0, 0, displayCanvas.width, displayCanvas.height);
        
        // 检查是否有任何内容需要绘制
        const hasContent = allOperations.length > 0 || currentStroke.length > 0 || currentEraseStroke.length > 0;
        
        if (hasContent) {
            displayCtx.globalCompositeOperation = 'source-over'; // 确保初始混合模式正常
            displayCtx.drawImage(offscreenCanvas, 0, 0);
            displayCtx.globalCompositeOperation = 'source-in';
            displayCtx.fillStyle = 'rgba(184, 140, 255, 0.6)';
            displayCtx.fillRect(0, 0, displayCanvas.width, displayCanvas.height);
        }
        
        // 重置混合模式并绘制点选和框选（在紫色遮罩之上）
        displayCtx.globalCompositeOperation = 'source-over';
        
        // 绘制点选模式的选中点（所有模式下都显示）
        if (selectedPoints.length > 0) {
            selectedPoints.forEach(point => {
                displayCtx.save();
                // 绘制白色边框
                displayCtx.fillStyle = 'rgba(255, 255, 255, 1)';
                displayCtx.beginPath();
                displayCtx.arc(point.displayX, point.displayY, 6, 0, 2 * Math.PI);
                displayCtx.fill();
                // 绘制红色内圆
                displayCtx.fillStyle = 'rgba(255, 0, 0, 0.8)';
                displayCtx.beginPath();
                displayCtx.arc(point.displayX, point.displayY, 4, 0, 2 * Math.PI);
                displayCtx.fill();
                displayCtx.restore();
            });
        }

        // 绘制绿色点（右键点击）
        if (greenPoints.length > 0) {
            greenPoints.forEach(point => {
                displayCtx.save();
                // 绘制白色边框
                displayCtx.fillStyle = 'rgba(255, 255, 255, 1)';
                displayCtx.beginPath();
                displayCtx.arc(point.displayX, point.displayY, 6, 0, 2 * Math.PI);
                displayCtx.fill();
                // 绘制绿色内圆
                displayCtx.fillStyle = 'rgba(0, 255, 0, 0.8)';
                displayCtx.beginPath();
                displayCtx.arc(point.displayX, point.displayY, 4, 0, 2 * Math.PI);
                displayCtx.fill();
                displayCtx.restore();
            });
        }
        
        // 绘制所有已完成的框选矩形
        selectionRects.forEach(rect => {
            if (rect.tlx !== undefined && rect.tly !== undefined && rect.brx !== undefined && rect.bry !== undefined) {
                // 将原图坐标转换为显示坐标
                const displayInfo = getCurrentDisplayInfo();
                const mediaElement = getMediaElement();
                const originalImageInfo = getMediaDimensions(mediaElement);
                
                if (displayInfo && originalImageInfo) {
                    const scaleX = displayInfo.displayWidth / originalImageInfo.width;
                    const scaleY = displayInfo.displayHeight / originalImageInfo.height;
                    
                    const displayTlx = rect.tlx * scaleX;
                    const displayTly = rect.tly * scaleY;
                    const displayBrx = rect.brx * scaleX;
                    const displayBry = rect.bry * scaleY;
                    const width = displayBrx - displayTlx;
                    const height = displayBry - displayTly;
                    
                    if (width > 0 && height > 0) {
                        displayCtx.save();
                        // 不需要应用变换，因为canvas已经通过CSS变换处理了缩放和位移
                        // 绘制半透明填充
                        displayCtx.fillStyle = 'rgba(0, 123, 255, 0.1)';
                        displayCtx.fillRect(displayTlx, displayTly, width, height);
                        // 绘制虚线边框
                        displayCtx.strokeStyle = 'rgba(0, 123, 255, 0.8)';
                        displayCtx.lineWidth = 2;
                        displayCtx.setLineDash([5, 5]);
                        displayCtx.strokeRect(displayTlx, displayTly, width, height);
                        displayCtx.setLineDash([]);
                        displayCtx.restore();
                    }
                }
            }
        });
        
        // 绘制当前正在绘制的框选矩形
        if (currentSelectionRect && currentSelectionRect.width > 0 && currentSelectionRect.height > 0) {
            displayCtx.save();
            // 不需要应用变换，因为canvas已经通过CSS变换处理了缩放和位移
            // 绘制半透明填充
            displayCtx.fillStyle = 'rgba(0, 123, 255, 0.1)';
            displayCtx.fillRect(currentSelectionRect.x, currentSelectionRect.y, currentSelectionRect.width, currentSelectionRect.height);
            // 绘制虚线边框
            displayCtx.strokeStyle = 'rgba(0, 123, 255, 0.8)';
            displayCtx.lineWidth = 2;
            displayCtx.setLineDash([5, 5]);
            displayCtx.strokeRect(currentSelectionRect.x, currentSelectionRect.y, currentSelectionRect.width, currentSelectionRect.height);
            displayCtx.setLineDash([]);
            displayCtx.restore();
        }
    }, [brushStrokes, eraseStrokes, currentStroke, currentEraseStroke, selectedSegment, toolSize, eraseMode, selectedPoints, greenPoints, selectionRects, currentSelectionRect]);

    // 处理重绘标志
    useEffect(() => {
        if (needsRedraw) {
            requestAnimationFrame(() => {
                redrawCanvas();
                setNeedsRedraw(false);
            });
        }
    }, [needsRedraw, redrawCanvas]);

    // 绘制笔画路径
    const drawStroke = (ctx, stroke, mode, strokeToolSize = toolSize) => {
        if (stroke.length < 1) return;
        
        ctx.save();
        
        // 设置绘制模式
        const isBrush = mode === 'brush';
        ctx.lineWidth = strokeToolSize;
        ctx.lineCap = 'round';
        ctx.lineJoin = 'round';
        
        if (isBrush) {
            
            // 第二步：绘制新内容（不透明度）
            ctx.globalCompositeOperation = 'source-over';
            ctx.strokeStyle = 'rgba(255, 255, 255, 1)';
            ctx.fillStyle = 'rgba(255, 255, 255, 1)';
            
            // 绘制新内容
            ctx.beginPath();
            if (stroke.length >= 2) {
                ctx.moveTo(stroke[0].x, stroke[0].y);
                for (let i = 1; i < stroke.length; i++) {
                    ctx.lineTo(stroke[i].x, stroke[i].y);
                }
                ctx.stroke();
            } else if (stroke.length === 1) {
                const radius = strokeToolSize / 2;
                ctx.beginPath();
                ctx.arc(stroke[0].x, stroke[0].y, radius, 0, 2 * Math.PI);
                ctx.fill();
            }
        } else {
            // 橡皮擦模式：直接清除
            ctx.globalCompositeOperation = 'destination-out';
            
            // 绘制路径或单点
            ctx.beginPath();
            if (stroke.length >= 2) {
                ctx.moveTo(stroke[0].x, stroke[0].y);
                for (let i = 1; i < stroke.length; i++) {
                    ctx.lineTo(stroke[i].x, stroke[i].y);
                }
                ctx.stroke();
            } else if (stroke.length === 1) {
                // 单点绘制
                const radius = strokeToolSize / 2;
                ctx.beginPath();
                ctx.arc(stroke[0].x, stroke[0].y, radius, 0, 2 * Math.PI);
                ctx.fill();
            }
        }
        
        ctx.restore();
    };

    // 重置媒体变换
    const resetMediaTransform = () => {
        setMediaScale(1);
        mediaScaleRef.current = 1;
        setMediaPosition({ x: 0, y: 0 });
        
        // 重置所有图片位置，包括layer图片
        const currentImageDiv = document.getElementById('current-image');
        const resetPositions = {
            currentImage: { x: 0, y: 0 },
            copy: { x: 0, y: 0 }
        };
        
        if (currentImageDiv) {
            const layerImages = currentImageDiv.querySelectorAll('img[data-key^="layer-"]');
            layerImages.forEach(img => {
                const key = img.getAttribute('data-key');
                if (key) {
                    resetPositions[key] = { x: 0, y: 0 };
                }
            });
        }
        
        setImagePositions(resetPositions);
    };

    // 获取当前离屏canvas图片，尺寸根据画幅比例设置
    const getCanvasImage = () => {
        // 使用通用函数获取媒体元素
        let mediaElement = getMediaElement();
        if (!mediaElement) {
            console.warn('媒体元素未找到');
            return null;
        }
        
        let targetWidth, targetHeight;
        // 如果有选中的画幅比例，使用对应的固定尺寸
        if (selectedRatio && selectedRatio.width && selectedRatio.height) {
            const { width, height } = selectedRatio;
            targetWidth = width;
            targetHeight = height;
        } else {
            // 否则使用媒体元素的原始尺寸
            const mediaDimensions = getMediaDimensions(mediaElement);
            if (!mediaDimensions) {
                console.warn('媒体元素未加载、尺寸无效或不支持的媒体类型');
                return null;
            }
            const { width: mediaWidth, height: mediaHeight } = mediaDimensions;
            targetWidth = mediaWidth;
            targetHeight = mediaHeight;
        }

        // 创建一个与目标尺寸相同的临时canvas
        const tempCanvas = document.createElement('canvas');
        tempCanvas.width = targetWidth;
        tempCanvas.height = targetHeight;
        const tempCtx = tempCanvas.getContext('2d');

        // 获取当前离屏canvas
        const offscreenCanvas = offscreenCanvasRef.current;
        if (!offscreenCanvas) {
            console.warn('离屏canvas未找到');
            return null;
        }

        // 先设置黑色背景
        tempCtx.fillStyle = 'rgba(0,0,0,1)';
        tempCtx.fillRect(0, 0, targetWidth, targetHeight);
        
        // 然后将离屏canvas内容缩放到目标尺寸
        tempCtx.drawImage(
            offscreenCanvas,
            0, 0, offscreenCanvas.width, offscreenCanvas.height,
            0, 0, targetWidth, targetHeight
        );

        // 返回base64格式的图片数据
        return tempCanvas.toDataURL('image/png');
    };

    // 重置缩放和位置
    useEffect(() => {
        if (!enableProcessing) {
            resetMediaTransform();
        }
    }, [enableProcessing]);

    // 监听selectedRatio变化，在canvas变化完成后重置图片位置和大小
    useEffect(() => {
        // 使用setTimeout确保canvas尺寸变化完成后再重置
        const timer = setTimeout(() => {
            resetMediaTransform();
        }, 0);
        
        return () => clearTimeout(timer);
    }, [selectedRatio]);

    // 父容器尺寸变化监听
    const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
    
    useEffect(() => {
        if (!mediaWrapperRef.current) return;
        
        const resizeObserver = new ResizeObserver((entries) => {
            for (const entry of entries) {
                const { width, height } = entry.contentRect;
                setContainerSize({ width, height });
            }
        });
        
        resizeObserver.observe(mediaWrapperRef.current);
        
        return () => {
            resizeObserver.disconnect();
        };
    }, [mediaWrapperRef.current, selectedRatio]);

    // Canvas尺寸变化监听和坐标缩放
    useEffect(() => {
        if (enableProcessing) {
            const displayInfo = getCurrentDisplayInfo();
            if (displayInfo) {
                const { displayWidth, displayHeight } = displayInfo;
                const newSize = { width: displayWidth, height: displayHeight };
                
                // 检查尺寸是否发生变化
                if (canvasSize.width !== newSize.width || canvasSize.height !== newSize.height) {
                    const oldSize = { ...canvasSize };
                    
                    // 如果不是初始化（oldSize不为0），则进行坐标缩放
                    if (oldSize.width > 0 && oldSize.height > 0) {
                        // 缩放画笔路径
                        const scaledBrushStrokes = scaleCoordinates(oldSize, newSize, brushStrokes);
                        setBrushStrokes(scaledBrushStrokes);
                        onBrushStrokesChange?.(scaledBrushStrokes);
                        
                        // 缩放擦除路径
                        const scaledEraseStrokes = scaleCoordinates(oldSize, newSize, eraseStrokes);
                        setEraseStrokes(scaledEraseStrokes);
                        onEraseStrokesChange?.(scaledEraseStrokes);
                        
                        // 缩放选中点（只缩放显示坐标，原图坐标保持不变）
                        if (selectedPoints.length > 0) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledSelectedPoints = selectedPoints.map(point => ({
                                ...point,
                                displayX: point.displayX * scaleX,
                                displayY: point.displayY * scaleY,
                                // 原图坐标保持不变
                                originalX: point.originalX,
                                originalY: point.originalY
                            }));
                            setSelectedPoints(scaledSelectedPoints);
                        }

                        // 缩放绿色点（只缩放显示坐标，原图坐标保持不变）
                        if (greenPoints.length > 0) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledGreenPoints = greenPoints.map(point => ({
                                ...point,
                                displayX: point.displayX * scaleX,
                                displayY: point.displayY * scaleY,
                                // 原图坐标保持不变
                                originalX: point.originalX,
                                originalY: point.originalY
                            }));
                            setGreenPoints(scaledGreenPoints);
                        }
                        
                        // 缩放框选区域（显示坐标缩放，原坐标不变）
                        if (selectionRects.length > 0) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledSelectionRects = selectionRects.map(rect => {
                                const scaledRect = { ...rect };
                                
                                // 处理x、y、width、height格式（显示坐标）
                                if (rect.x !== undefined && rect.y !== undefined) {
                                    scaledRect.x = rect.x * scaleX;
                                    scaledRect.y = rect.y * scaleY;
                                    scaledRect.width = rect.width * scaleX;
                                    scaledRect.height = rect.height * scaleY;
                                }
                                
                                // tlx、tly、brx、bry是原图坐标，不需要缩放
                                // 这些坐标在绘制时会通过mediaScale进行显示调整
                                
                                return scaledRect;
                            });
                            setSelectionRects(scaledSelectionRects);
                        }
                        
                        // 缩放当前正在绘制的框选区域
                        if (currentSelectionRect) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledCurrentSelectionRect = {
                                ...currentSelectionRect,
                                x: currentSelectionRect.x * scaleX,
                                y: currentSelectionRect.y * scaleY,
                                width: currentSelectionRect.width * scaleX,
                                height: currentSelectionRect.height * scaleY
                            };
                            setCurrentSelectionRect(scaledCurrentSelectionRect);
                        }
                        
                        // 缩放框选起始点
                        if (isRectSelecting) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            setRectStart(prev => ({
                                x: prev.x * scaleX,
                                y: prev.y * scaleY
                            }));
                        }
                        
                        // 缩放当前正在绘制的路径
                        if (currentStroke.length > 0) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledCurrentStroke = currentStroke.map(point => ({
                                x: point.x * scaleX,
                                y: point.y * scaleY
                            }));
                            setCurrentStroke(scaledCurrentStroke);
                        }
                        
                        if (currentEraseStroke.length > 0) {
                            const scaleX = newSize.width / oldSize.width;
                            const scaleY = newSize.height / oldSize.height;
                            const scaledCurrentEraseStroke = currentEraseStroke.map(point => ({
                                x: point.x * scaleX,
                                y: point.y * scaleY
                            }));
                            setCurrentEraseStroke(scaledCurrentEraseStroke);
                        }
                        
                        // 缩放图片位置和尺寸
                        const scaleX = newSize.width / oldSize.width;
                        const scaleY = newSize.height / oldSize.height;
                        
                        // 缩放图片位置
                        setImagePositions(prevPositions => {
                            const scaledPositions = {};
                            Object.keys(prevPositions).forEach(key => {
                                const pos = prevPositions[key];
                                scaledPositions[key] = {
                                    x: pos.x * scaleX,
                                    y: pos.y * scaleY
                                };
                            });
                            return scaledPositions;
                        });
                        // 缩放图片尺寸
                        setImageSizes(prevSizes => {
                            const scaledSizes = {};
                            Object.keys(prevSizes).forEach(key => {
                                const size = prevSizes[key];
                                scaledSizes[key] = {
                                    width: size.width * scaleX ,
                                    height: size.height * scaleX
                                };
                            });
                            return scaledSizes;
                        });
                    }
                    
                    // 更新Canvas尺寸状态
                    setCanvasSize(newSize);
                    prevCanvasSizeRef.current = oldSize;
                    
                    // 触发图片样式更新，确保图片尺寸与Canvas尺寸同步
                    if (onMediaStyleChange) {
                        // 使用setTimeout确保状态更新完成后再计算样式
                        setTimeout(() => {
                            const mediaStyle = getCurrentMediaStyle();
                            onMediaStyleChange(mediaStyle);
                        }, 0);
                    }
                }
            }
        }
    }, [enableProcessing, containerSize, brushStrokes, eraseStrokes, currentStroke, currentEraseStroke, selectedPoints, greenPoints, selectedRatio]);

    // Canvas重绘监听 - 使用requestAnimationFrame优化性能
    useEffect(() => {
        if (enableProcessing && canvasRef.current) {
            let animationId;
            const scheduleRedraw = () => {
                if (animationId) {
                    cancelAnimationFrame(animationId);
                }
                animationId = requestAnimationFrame(() => {
                    redrawCanvas();
                    animationId = null;
                });
            };
            scheduleRedraw();
            
            return () => {
                if (animationId) {
                    cancelAnimationFrame(animationId);
                }
            };
        }
    }, [brushStrokes, currentStroke, eraseStrokes, currentEraseStroke, enableProcessing, canvasSize.width, canvasSize.height, selectedPoints, greenPoints, selectionRects, currentSelectionRect, selectedRatio]);

    // 监听工具模式变化，切换工具时清除画布内容
    useEffect(() => {
        if (prevEraseMode !== eraseMode) {
            // 清除点选内容
            setSelectedPoints([]);
        setGreenPoints([]);
            // 清除框选内容
            setSelectionRects([]);
            setCurrentSelectionRect(null);
            setIsRectSelecting(false);
            // 清除画笔轨迹
            setBrushStrokes([]);
            setCurrentStroke([]);
            // 清除橡皮擦轨迹
            setEraseStrokes([]);
            setCurrentEraseStroke([]);
            // 通知父组件轨迹变化
            onBrushStrokesChange?.([]);
            onEraseStrokesChange?.([]);
            // 更新上一次的模式
            setPrevEraseMode(eraseMode);
        }
    }, [eraseMode, prevEraseMode, onBrushStrokesChange, onEraseStrokesChange]);

    // 处理鼠标进入
    const handleMouseEnter = () => {
        if (enableProcessing && eraseMode === EDIT_MODES.ERASER) {
            setShowEraserPreview(true);
        } else if (enableProcessing && eraseMode === EDIT_MODES.BRUSH) {
            setShowBrushPreview(true);
        }
    };

    // 处理鼠标离开
    const handleMouseLeave = () => {
        setShowEraserPreview(false);
        setShowBrushPreview(false);
        if (enableProcessing) {
            handleMouseUp();
        }
    };

    // 获取鼠标事件处理器
    const getMouseHandlers = () => {
        // 创建组合的鼠标按下处理器
        const combinedMouseDown = (e) => {
            // 优先处理拖动（空格键按下时或DRAG模式时）
            if (isSpacePressed || eraseMode === EDIT_MODES.DRAG) {
                handleMouseDown(e);
                return;
            }
            
            // 其他工具的处理
            if (enableProcessing && eraseMode === EDIT_MODES.BRUSH) {
                handleBrushStart(e);
            } else if (enableProcessing && eraseMode === EDIT_MODES.ERASER) {
                handleEraseStart(e);
            } else if (enableProcessing && eraseMode === EDIT_MODES.POINT) {
                handlePointStart(e);
            } else if (enableProcessing && eraseMode === EDIT_MODES.RECT) {
                handleRectStart(e);
            }
        };
        
        // 创建组合的鼠标移动处理器
        const combinedMouseMove = (e) => {
            // 优先处理拖动
            if (isDragging) {
                handleMouseMove(e);
                return;
            }
            
            // 其他工具的处理
            if (enableProcessing && eraseMode === EDIT_MODES.BRUSH) {
                handleBrushMove(e);
            } else if (enableProcessing && eraseMode === EDIT_MODES.ERASER) {
                handleEraseMove(e);
            } else if (enableProcessing && eraseMode === EDIT_MODES.RECT) {
                handleRectMove(e);
            }
        };
        
        return {
            onMouseDown: enableProcessing ? combinedMouseDown : undefined,
            onMouseMove: enableProcessing ? combinedMouseMove : undefined,
            onMouseUp: enableProcessing ? handleMouseUp : undefined,
            onMouseEnter: handleMouseEnter,
            onMouseLeave: handleMouseLeave,
            onContextMenu: enableProcessing && eraseMode === EDIT_MODES.POINT ? handleGreenPointStart : undefined
        };
    };

    // 获取媒体样式
    const getMediaStyle = () => {
        return {
            transform: enableProcessing ? `scale(${mediaScale}) translate(${mediaPosition.x}px, ${mediaPosition.y}px)` : 'none',
            transformOrigin: 'center center',
            // 拖动或缩放时禁用动画，提供即时响应
            transition: (isDragging || isScaling) ? 'none' : 'transform 0.1s ease-out',
            imagePositions: imagePositions
        };
    };

    // selectedRatio模式专用的媒体样式计算函数
    const getSelectedRatioMediaStyle = () => {
        if (!enableProcessing) {
            return { transform: 'none' };
        }
        
        const displayInfo = getCurrentDisplayInfo();
        if (!displayInfo) {
            return { transform: 'none' };
        }
        
        const { displayWidth, displayHeight } = displayInfo;
        
        // 为每个图层计算独立的样式
        const layerStyles = {};
        
        // 获取所有图片元素
        const mediaContainer = document.getElementById(mediaElementId);
        if (mediaContainer) {
            const imageElements = mediaContainer.querySelectorAll('img[data-key]');
            
            imageElements.forEach(img => {
                const layerKey = img.getAttribute('data-key');
                if (layerKey && img.naturalWidth && img.naturalHeight) {
                    // 优先使用调整后的尺寸，如果没有则使用原始尺寸
                    const adjustedSize = imageSizes[layerKey];
                    const mediaWidth = adjustedSize ? adjustedSize.width : img.naturalWidth;
                    const mediaHeight = adjustedSize ? adjustedSize.height : img.naturalHeight;
                    // 计算每个图片的显示尺寸
                    let imgDisplayWidth, imgDisplayHeight;
                    if (mediaWidth > displayWidth || mediaHeight > displayHeight) {
                        // 如果图片尺寸超过显示画布，按比例缩放以适应画布
                        const scaleByWidth = displayWidth / mediaWidth;
                        const scaleByHeight = displayHeight / mediaHeight;
                        const scale = Math.min(scaleByWidth, scaleByHeight);

                        imgDisplayWidth = mediaWidth * scale;
                        imgDisplayHeight = mediaHeight * scale;
                    }else {
                        // 如果图片尺寸没有超过显示画布，使用原图尺寸
                        imgDisplayWidth = mediaWidth;
                        imgDisplayHeight = mediaHeight;
                    }
                    layerStyles[layerKey] = {
                        width: imgDisplayWidth,
                        height: imgDisplayHeight
                    };
                }
            });
        }
        
        // 应用缩放和位移
        const finalScale = mediaScaleRef.current;
        
        // 在selectedRatio模式下，使用mediaPosition保持画布和图片位置同步
        const translateX = Math.round(mediaPosition.x);
        const translateY = Math.round(mediaPosition.y);
        return {
            transform: `scale(${finalScale}) translate(${translateX}px, ${translateY}px)`,
            transformOrigin: 'center center',
            // 拖动或缩放时禁用动画，提供即时响应
            transition: (isDragging || isScaling) ? 'none' : 'transform 0.1s ease-out',
            borderRadius: 0,
            position: 'absolute',
            left: '50%',
            top: '50%',
            imagePositions: imagePositions,
            layerStyles: layerStyles // 包含每个图层的独立样式
        };
    };

    // 获取当前模式下的媒体样式
    const getCurrentMediaStyle = () => {
        return selectedRatio ? getSelectedRatioMediaStyle() : getMediaStyle();
    };

    // 渲染Canvas层（双Canvas架构）
    const renderCanvas = () => {
        if (!enableProcessing) return null;
        
        // 直接使用canvasSize状态，确保与useEffect中的尺寸计算保持同步
        const { width: canvasWidth, height: canvasHeight } = canvasSize;
        
        // 如果Canvas尺寸还未初始化，不渲染
        if (canvasWidth <= 0 || canvasHeight <= 0) return null;
        
        return (
            <>
                {/* 离屏Canvas - 用于绘制（隐藏） */}
                <canvas
                    ref={offscreenCanvasRef}
                    width={canvasWidth}
                    height={canvasHeight}
                    style={{
                        position: 'absolute',
                        top: -9999, // 隐藏离屏Canvas
                        left: -9999,
                        pointerEvents: 'none'
                    }}
                />
                {/* 显示Canvas - 用于显示和交互 */}
                <canvas
                    ref={canvasRef}
                    width={canvasWidth}
                    height={canvasHeight}
                    style={{
                        position: 'absolute',
                        width: canvasWidth,
                        height: canvasHeight,
                        zIndex: 10,
                        transform: `scale(${mediaScale}) translate(${mediaPosition.x}px, ${mediaPosition.y}px)`,
                        transformOrigin: 'center center',
                        // 拖动或缩放时禁用动画，提供即时响应
                        transition: (isDragging || isScaling) ? 'none' : 'transform 0.1s ease-out',
                        display: hideDisplayCanvas ? 'none' : 'block',
                        left: '50%',
                        top: '50%',
                        marginLeft: -canvasWidth / 2,
                        marginTop: -canvasHeight / 2
                    }}
                />
            </>
        );
    };
    // 渲染Canvas层（双Canvas架构）
    const renderbaseMap = () => {
        if (!enableProcessing) return null;
        
        // 直接使用canvasSize状态，确保与useEffect中的尺寸计算保持同步
        const { width: canvasWidth, height: canvasHeight } = canvasSize;
        
        // 如果Canvas尺寸还未初始化，不渲染
        if (canvasWidth <= 0 || canvasHeight <= 0) return null;
        
        return (
            <>
                {/* 棋盘格背景层 - 最底层 */}
                <div
                    style={{
                        position: 'absolute',
                        width: canvasWidth,
                        height: canvasHeight,
                        zIndex: 0,
                        transform: `scale(${mediaScale}) translate(${mediaPosition.x}px, ${mediaPosition.y}px)`,
                        transformOrigin: 'center center',
                        // 拖动或缩放时禁用动画，提供即时响应
            transition: (isDragging || isScaling) ? 'none' : 'transform 0.1s ease-out',
                        display: hideDisplayCanvas ? 'none' : 'block',
                        left: '50%',
                        top: '50%',
                        marginLeft: -canvasWidth / 2,
                        marginTop: -canvasHeight / 2,
                        backgroundImage: `
                            linear-gradient(45deg, rgba(100, 100, 100, 0.3) 25%, transparent 25%),
                            linear-gradient(-45deg, rgba(100, 100, 100, 0.3) 25%, transparent 25%),
                            linear-gradient(45deg, transparent 75%, rgba(100, 100, 100, 0.3) 75%),
                            linear-gradient(-45deg, transparent 75%, rgba(100, 100, 100, 0.3) 75%)
                        `,
                        backgroundSize: '16px 16px',
                        backgroundPosition: '0 0, 0 8px, 8px -8px, -8px 0px',
                        backgroundColor: 'rgba(30, 30, 30, 0.9)'
                    }}
                />
            </>
        );
    };

    // 渲染重置按钮
    const renderResetButton = () => {
        if (!enableProcessing || (mediaScale === 1 && mediaPosition.x === 0 && mediaPosition.y === 0)) {
            return null;
        }
        
        return (
            <button
                className={styles.resetButton}
                onClick={resetMediaTransform}
                title="重置媒体位置和缩放"
            >
                重置
            </button>
        );
    };

    // 渲染控制点 - 使用useMemo优化性能，避免多次渲染
    const renderResizeHandles = useMemo(() => {
        // 只在DRAG模式、selectedRatio模式下且有选中图片时显示控制点，缩放时隐藏控制点
        if (eraseMode !== EDIT_MODES.DRAG || !selectedRatio || !selectedImageKey || isDragging || isScaling) {
            return null;
        }

        const targetImageKey = selectedImageKey;
        if (!imagePositions[targetImageKey]) {
            return null;
        }
        const imageSize = imageSizes[targetImageKey];
        if (!imageSize) {
            return null;
        }

        // 获取图片的实际DOM位置，确保控制点与实际显示完全匹配
        const containerRect = mediaWrapperRef.current?.getBoundingClientRect();
        if (!containerRect) return null;
        
        // 通过DOM查询获取图片的实际位置和尺寸
        const targetImg = document.getElementById(mediaElementId)?.querySelector(`img[data-key="${targetImageKey}"]`);
        if (!targetImg) return null;
        const imgRect = targetImg.getBoundingClientRect();
        
        // 计算图片相对于容器的位置
        const centerX = imgRect.left - containerRect.left + imgRect.width / 2;
        const centerY = imgRect.top - containerRect.top + imgRect.height / 2;
        const halfWidth = imgRect.width / 2;
        const halfHeight = imgRect.height / 2;

        // 定义控制点位置
        const handles = [
            { type: RESIZE_HANDLES.TOP_LEFT, x: centerX - halfWidth, y: centerY - halfHeight, cursor: 'nw-resize' },
            { type: RESIZE_HANDLES.TOP_RIGHT, x: centerX + halfWidth, y: centerY - halfHeight, cursor: 'ne-resize' },
            { type: RESIZE_HANDLES.BOTTOM_LEFT, x: centerX - halfWidth, y: centerY + halfHeight, cursor: 'sw-resize' },
            { type: RESIZE_HANDLES.BOTTOM_RIGHT, x: centerX + halfWidth, y: centerY + halfHeight, cursor: 'se-resize' },
            { type: RESIZE_HANDLES.TOP, x: centerX, y: centerY - halfHeight, cursor: 'n-resize' },
            { type: RESIZE_HANDLES.BOTTOM, x: centerX, y: centerY + halfHeight, cursor: 's-resize' },
            { type: RESIZE_HANDLES.LEFT, x: centerX - halfWidth, y: centerY, cursor: 'w-resize' },
            { type: RESIZE_HANDLES.RIGHT, x: centerX + halfWidth, y: centerY, cursor: 'e-resize' }
        ];

        return handles.map(handle => (
            <div
                key={handle.type}
                style={{
                    position: 'absolute',
                    left: handle.x - HANDLE_SIZE / 2,
                    top: handle.y - HANDLE_SIZE / 2,
                    width: HANDLE_SIZE,
                    height: HANDLE_SIZE,
                    cursor: handle.cursor,
                    zIndex: 20,
                    ...HANDLE_STYLE
                }}
                onMouseDown={(e) => handleResizeStart(e, handle.type)}
            />
        ));
    }, [eraseMode, selectedRatio, selectedImageKey, isDragging, isScaling, imagePositions, imageSizes, mediaScale, forceUpdateControlPoints]);

    // 开始调整大小
    const handleResizeStart = (e, handleType) => {
        e.preventDefault();
        e.stopPropagation();


        if (!selectedImageKey || !imagePositions[selectedImageKey] || !imageSizes[selectedImageKey]) {    
            return;
        }
        
        const imagePosition = imagePositions[selectedImageKey];
        const imageWidth=document.querySelector(`img[data-key="${selectedImageKey}"]`).width
        const imageHeight=document.querySelector(`img[data-key="${selectedImageKey}"]`).height
        const startData = {
            startX: e.clientX,
            startY: e.clientY,
            startPosition: { ...imagePosition },
            startSize: { width:imageWidth,height:imageHeight },
            aspectRatio: imageWidth / imageHeight
        };
        
        setResizeHandle(handleType);
        setResizeStartData(startData);
        

        // 创建带有当前数据的事件处理函数
        const handleMove = (moveEvent) => handleResizeMove(moveEvent, startData, handleType);
        const handleEnd = () => {
            handleResizeEnd();
            document.removeEventListener('mousemove', handleMove);
            document.removeEventListener('mouseup', handleEnd);
        };

        // 添加全局鼠标事件监听
        document.addEventListener('mousemove', handleMove);
        document.addEventListener('mouseup', handleEnd);
    };

    // 调整大小过程中
    const handleResizeMove = (e, startData = resizeStartData, handleType = resizeHandle) => {
        
        if (!startData || !selectedImageKey) {    
            return;
        }

        const deltaX = (e.clientX - startData.startX) / mediaScale;
        const deltaY = (e.clientY - startData.startY) / mediaScale;
        
        
        let newSize = { ...startData.startSize };
        let newPosition = { ...startData.startPosition };
        // 获取容器尺寸限制
        let containerWidth = Infinity;
        let containerHeight = Infinity;
        
        if (selectedRatio) {
            const displayInfo = calculateSelectedRatioDisplayInfo();
            if (displayInfo) {
                containerWidth = displayInfo.displayWidth;
                containerHeight = displayInfo.displayHeight;
            }
        }
        
        // 根据控制点类型调整尺寸和位置
        switch (handleType) {
            case RESIZE_HANDLES.TOP_LEFT:
                // 左上角：按比例调整，保持宽高比
                {
                    const aspectRatio = startData.startSize.width / startData.startSize.height;
                    const avgDelta = -(deltaX + deltaY) / 2; // 取平均值并反向
                    newSize.width = startData.startSize.width + avgDelta;
                    newSize.height = newSize.width / aspectRatio;
                    newPosition.x = startData.startPosition.x - (newSize.width - startData.startSize.width) / 2;
                    newPosition.y = startData.startPosition.y - (newSize.height - startData.startSize.height) / 2;
                }
                break;
            case RESIZE_HANDLES.TOP_RIGHT:
                // 右上角：按比例调整，保持宽高比
                {
                    const aspectRatio = startData.startSize.width / startData.startSize.height;
                    const avgDelta = (deltaX - deltaY) / 2; // 右增左减，上减下增
                    newSize.width = startData.startSize.width + avgDelta;
                    newSize.height = newSize.width / aspectRatio;
                    newPosition.x = startData.startPosition.x + (newSize.width - startData.startSize.width) / 2;
                    newPosition.y = startData.startPosition.y - (newSize.height - startData.startSize.height) / 2;
                }
                break;
            case RESIZE_HANDLES.BOTTOM_LEFT:
                // 左下角：按比例调整，保持宽高比
                {
                    const aspectRatio = startData.startSize.width / startData.startSize.height;
                    const avgDelta = (-deltaX + deltaY) / 2; // 左减右增，下增上减
                    newSize.width = startData.startSize.width + avgDelta;
                    newSize.height = newSize.width / aspectRatio;
                    newPosition.x = startData.startPosition.x - (newSize.width - startData.startSize.width) / 2;
                    newPosition.y = startData.startPosition.y + (newSize.height - startData.startSize.height) / 2;
                }
                break;
            case RESIZE_HANDLES.BOTTOM_RIGHT:
                // 右下角：按比例调整，保持宽高比
                {
                    const aspectRatio = startData.startSize.width / startData.startSize.height;
                    const avgDelta = (deltaX + deltaY) / 2; // 取平均值
                    newSize.width = startData.startSize.width + avgDelta;
                    newSize.height = newSize.width / aspectRatio;
                    newPosition.x = startData.startPosition.x + (newSize.width - startData.startSize.width) / 2;
                    newPosition.y = startData.startPosition.y + (newSize.height - startData.startSize.height) / 2;
                }
                break;
            case RESIZE_HANDLES.TOP:
                // 顶部调整：向上拖拽减少高度，向下拖拽增加高度，保持底边固定
                newSize.height = startData.startSize.height - deltaY;
                newPosition.y = startData.startPosition.y + deltaY / 2;
                break;
            case RESIZE_HANDLES.BOTTOM:
                // 底部调整：只改变高度，位置不变，保持顶边固定
                newSize.height = startData.startSize.height + deltaY;
                newPosition.y = startData.startPosition.y + deltaY / 2;
                break;
            case RESIZE_HANDLES.LEFT:
                // 左边调整：向左拖拽增加宽度，向右拖拽减少宽度，保持右边固定
                newSize.width = startData.startSize.width - deltaX;
                newPosition.x = startData.startPosition.x + deltaX / 2;
                break;
            case RESIZE_HANDLES.RIGHT:
                // 右边调整：只改变宽度，位置不变，保持左边固定
                newSize.width = startData.startSize.width + deltaX;
                newPosition.x = startData.startPosition.x + deltaX / 2;
                break;
        }
        
        // 确保调整后的图片不超出容器边界，并添加边界吸附功能
        if (selectedRatio && containerWidth !== Infinity && containerHeight !== Infinity) {
            // 计算图片的边界位置
            let leftBound = newPosition.x - newSize.width / 2;
            let rightBound = newPosition.x + newSize.width / 2;
            let topBound = newPosition.y - newSize.height / 2;
            let bottomBound = newPosition.y + newSize.height / 2;
            
            // 容器边界
            const containerLeft = -containerWidth / 2;
            const containerRight = containerWidth / 2;
            const containerTop = -containerHeight / 2;
            const containerBottom = containerHeight / 2;
            
            // 边界吸附逻辑：当图片边界接近容器边界时自动吸附
            const snapThreshold = 10; // 吸附阈值（像素）
            
            // 特殊处理：当四个边都离边界10像素以内时，直接设置为容器大小
            if (Math.abs(leftBound - containerLeft) <= snapThreshold &&
                Math.abs(rightBound - containerRight) <= snapThreshold &&
                Math.abs(topBound - containerTop) <= snapThreshold &&
                Math.abs(bottomBound - containerBottom) <= snapThreshold) {
                newSize.width = containerWidth;
                newSize.height = containerHeight;
                newPosition.x = 0; // 水平居中
                newPosition.y = 0; // 垂直居中
                // 重新计算边界位置以保持一致性
                leftBound = newPosition.x - newSize.width / 2;
                rightBound = newPosition.x + newSize.width / 2;
                topBound = newPosition.y - newSize.height / 2;
                bottomBound = newPosition.y + newSize.height / 2;
            } else {
                // 左边界吸附
                if (Math.abs(leftBound - containerLeft) <= snapThreshold) {
                    const adjustment = containerLeft - leftBound;
                    newPosition.x += adjustment;
                    leftBound = containerLeft;
                    rightBound += adjustment;
                }
            
                // 右边界吸附
                if (Math.abs(rightBound - containerRight) <= snapThreshold) {
                    const adjustment = containerRight - rightBound;
                    newPosition.x += adjustment;
                    rightBound = containerRight;
                    leftBound += adjustment;
                }
                
                // 上边界吸附
                if (Math.abs(topBound - containerTop) <= snapThreshold) {
                    const adjustment = containerTop - topBound;
                    newPosition.y += adjustment;
                    topBound = containerTop;
                    bottomBound += adjustment;
                }
                
                // 下边界吸附
                if (Math.abs(bottomBound - containerBottom) <= snapThreshold) {
                    const adjustment = containerBottom - bottomBound;
                    newPosition.y += adjustment;
                    bottomBound = containerBottom;
                    topBound += adjustment;
                }
            }
            
            // 重新计算边界位置（吸附后）
            leftBound = newPosition.x - newSize.width / 2;
            rightBound = newPosition.x + newSize.width / 2;
            topBound = newPosition.y - newSize.height / 2;
            bottomBound = newPosition.y + newSize.height / 2;
            
            // 特殊情况处理：当左右边界都吸附时，宽度设置为画布宽度
            if (Math.abs(leftBound - containerLeft) <= 10 && Math.abs(rightBound - containerRight) <= 10) {
                newSize.width = containerWidth;
                newPosition.x = 0; // 居中
                // 重新计算边界位置以保持一致性
                leftBound = newPosition.x - newSize.width / 2;
                rightBound = newPosition.x + newSize.width / 2;
            }
            
            // 特殊情况处理：当上下边界都吸附时，高度设置为画布高度
            if (Math.abs(topBound - containerTop) <= 10 && Math.abs(bottomBound - containerBottom) <= 10) {
                newSize.height = containerHeight;
                newPosition.y = 0; // 居中
                // 重新计算边界位置以保持一致性
                topBound = newPosition.y - newSize.height / 2;
                bottomBound = newPosition.y + newSize.height / 2;
            }
            
            // 特殊情况处理：当四个边界都吸附时（斜边），尺寸设置为画布尺寸
            if (Math.abs(leftBound - containerLeft) <= 10 && Math.abs(rightBound - containerRight) <= 10 &&
                Math.abs(topBound - containerTop) <= 10 && Math.abs(bottomBound - containerBottom) <= 10) {
                newSize.width = containerWidth;
                newSize.height = containerHeight;
                newPosition.x = 0; // 水平居中
                newPosition.y = 0; // 垂直居中
                // 重新计算边界位置以保持一致性
                leftBound = newPosition.x - newSize.width / 2;
                rightBound = newPosition.x + newSize.width / 2;
                topBound = newPosition.y - newSize.height / 2;
                bottomBound = newPosition.y + newSize.height / 2;
            }
            // 根据不同的控制点类型进行边界检测（当图片已到达边界时，阻止进一步操作）
            const tolerance = -10; // 允许完全贴合边界
            
            // 检查是否已经到达边界，如果是则直接返回，不进行任何操作和计算
            if (handleType == RESIZE_HANDLES.LEFT && leftBound <= containerLeft + tolerance) {
                return; // 图片左边界已到达容器左边界，停止操作
            }
            
            if (handleType == RESIZE_HANDLES.RIGHT && rightBound >= containerRight - tolerance) {
                return; // 图片右边界已到达容器右边界，停止操作
            }
            
            if (handleType == RESIZE_HANDLES.TOP && topBound <= containerTop + tolerance) {
                return; // 图片上边界已到达容器上边界，停止操作
            }
            if (handleType == RESIZE_HANDLES.BOTTOM && bottomBound >= containerBottom - tolerance) {
                return; // 图片下边界已到达容器下边界，停止操作
            }
            
            // 处理角落控制点 - 需要同时检查水平和垂直边界
            if (handleType == RESIZE_HANDLES.TOP_LEFT) {
                if (leftBound <= containerLeft + tolerance || topBound <= containerTop + tolerance) {
                    return; // 图片左边界或上边界已到达容器边界，停止操作
                }
            }
            
            if (handleType == RESIZE_HANDLES.TOP_RIGHT) {
                if (rightBound >= containerRight - tolerance || topBound <= containerTop + tolerance) {
                    return; // 图片右边界或上边界已到达容器边界，停止操作
                }
            }
            
            if (handleType == RESIZE_HANDLES.BOTTOM_LEFT) {
                if (leftBound <= containerLeft + tolerance || bottomBound >= containerBottom - tolerance) {
                    return; // 图片左边界或下边界已到达容器边界，停止操作
                }
            }
            
            if (handleType == RESIZE_HANDLES.BOTTOM_RIGHT) {
                if (rightBound >= containerRight - tolerance || bottomBound >= containerBottom - tolerance) {
                    return; // 图片右边界或下边界已到达容器边界，停止操作
                }
            }
        }
        // 直接更新图片容器的DOM样式，同时更新transform中的translate来保持中心位置
        const mediaContainer = document.getElementById(mediaElementId);
        if (mediaContainer) {
            const targetImg = mediaContainer.querySelector(`img[data-key="${selectedImageKey}"]`);
            if (targetImg && targetImg.parentElement) {
                // 更新父容器尺寸
                targetImg.parentElement.style.width = `${newSize.width}px`;
                targetImg.parentElement.style.height = `${newSize.height}px`;
            }
        }
        // 更新位置和尺寸状态
        setImagePositions(prev => ({
            ...prev,
            [selectedImageKey]: newPosition
        }));
        setImageSizes(prev => ({
            ...prev,
            [selectedImageKey]: newSize
        }));
    };

    // 结束调整大小
    const handleResizeEnd = () => {
        setResizeHandle(null);
        setResizeStartData(null);
        
        // 移除全局鼠标事件监听
        document.removeEventListener('mousemove', handleResizeMove);
        document.removeEventListener('mouseup', handleResizeEnd);
        
        // 强制更新控制点位置，确保拖动结束后控制点正确对齐
        setTimeout(() => {
            // 触发控制点重新计算，通过更新一个依赖项来强制重新渲染
            setForceUpdateControlPoints(prev => prev + 1);
        }, 50);
    };

    // 清除选中的点
    const clearSelectedPoints = () => {
        setSelectedPoints([]);
        setGreenPoints([]);
    };

    // 下载调整尺寸后的图片，保持原图片在对应位置
    const handleDownloadResizedImage = async () => {
        try {
            if (!selectedRatio) {
                return;
            }
            const newWidth = selectedRatio.width;
            const newHeight = selectedRatio.height;    

            // 获取图片容器元素（通过ID选择器）
            const containerElement = document.getElementById('current-image');    
            
            if (!containerElement) {
                console.error('未找到图片容器元素');
                return;
            }
            
            // 获取容器内的所有图片元素
            const imgElements = containerElement.querySelectorAll('img');    
            
            if (imgElements.length === 0) {
                console.error('容器内未找到图片元素');
                return;
            }
            
            // 获取显示画布的实际尺寸
            const displayCanvas = canvasRef.current;
            if (!displayCanvas) {
                console.error('未找到显示画布');
                return;
            }
            const displayWidth = displayCanvas.width;
            const displayHeight = displayCanvas.height;    
            
            try {
                // 创建离屏canvas进行合成
                const offscreenCanvas = document.createElement('canvas');
                const ctx = offscreenCanvas.getContext('2d');
                
                // 设置新的canvas尺寸
                offscreenCanvas.width = newWidth;
                offscreenCanvas.height = newHeight;
                
                // 计算显示画布到新画布的缩放比例
                const scaleX = newWidth / displayWidth;
                const scaleY = newHeight / displayHeight;        
                
                // 设置黑色背景
                ctx.fillStyle = '#000000';
                ctx.fillRect(0, 0, newWidth, newHeight);
                
                // 遍历所有图片元素并绘制到canvas上
                for (let i = 0; i < imgElements.length; i++) {
                    const imgElement = imgElements[i];
                    const imgKey = imgElement.getAttribute('data-key');            
                    
                    // 获取当前媒体样式，包含正确的图片尺寸信息
                    const currentMediaStyle = getCurrentMediaStyle();
                    const layerStyles = currentMediaStyle.layerStyles || {};
                    
                    // 使用layerStyles中计算好的尺寸，这已经考虑了用户的调整
                    let baseWidth, baseHeight;
                    if (imgKey && layerStyles[imgKey]) {
                        baseWidth = layerStyles[imgKey].width;
                        baseHeight = layerStyles[imgKey].height;
                    } else {
                        // 如果没有找到layerStyles，回退到自然尺寸计算
                        const naturalWidth = imgElement.naturalWidth || imgElement.width;
                        const naturalHeight = imgElement.naturalHeight || imgElement.height;
                        
                        if (!naturalWidth || !naturalHeight) {
                            console.warn(`第${i + 1}个图片尺寸无效，跳过`);
                            continue;
                        }
                        
                        // 计算图片在显示画布中的基础尺寸（保持宽高比，适应画布）
                        const imgAspectRatio = naturalWidth / naturalHeight;
                        const canvasAspectRatio = displayWidth / displayHeight;
                        
                        if (imgAspectRatio > canvasAspectRatio) {
                            // 图片更宽，以宽度为准
                            baseWidth = displayWidth;
                            baseHeight = displayWidth / imgAspectRatio;
                        } else {
                            // 图片更高，以高度为准
                            baseHeight = displayHeight;
                            baseWidth = displayHeight * imgAspectRatio;
                        }
                    }
                    
                    // 计算图片在显示画布中的居中位置
                    const baseX = (displayWidth - baseWidth) / 2;
                    const baseY = (displayHeight - baseHeight) / 2;
                    
                    // 获取图片的个别位置偏移（如果有的话）
                    let offsetX = 0, offsetY = 0;
                    if (imgKey && imagePositions[imgKey]) {
                        const position = imagePositions[imgKey];
                        offsetX = position.x;
                        offsetY = position.y;
                    }
                    
                    // 下载时使用原始尺寸和位置，不应用显示缩放
                    const finalWidth = baseWidth;
                    const finalHeight = baseHeight;
                    const finalX = baseX + offsetX;
                    const finalY = baseY + offsetY;
                    
                    // 转换到目标下载尺寸
                    const newX = finalX * scaleX;
                    const newY = finalY * scaleY;
                    const newImgWidth = finalWidth * scaleX;
                    const newImgHeight = finalHeight * scaleY;
                    
                    // 计算图片的原始宽高比
                    const imgNaturalWidth = imgElement.naturalWidth || imgElement.width;
                    const imgNaturalHeight = imgElement.naturalHeight || imgElement.height;
                    const imgAspectRatio = imgNaturalWidth / imgNaturalHeight;
                    
                    // 计算目标区域的宽高比
                    const targetAspectRatio = newImgWidth / newImgHeight;
                    
                    // 模拟 object-fit: cover 的行为，确保裁剪坐标为整数
                    let sourceX = 0, sourceY = 0, sourceWidth = imgNaturalWidth, sourceHeight = imgNaturalHeight;
                    
                    if (imgAspectRatio > targetAspectRatio) {
                        // 图片更宽，需要裁剪左右两边
                        sourceWidth = Math.round(imgNaturalHeight * targetAspectRatio);
                        sourceX = Math.round((imgNaturalWidth - sourceWidth) / 2);
                    } else if (imgAspectRatio < targetAspectRatio) {
                        // 图片更高，需要裁剪上下两边
                        sourceHeight = Math.round(imgNaturalWidth / targetAspectRatio);
                        sourceY = Math.round((imgNaturalHeight - sourceHeight) / 2);
                    }
                    
                    // 使用裁剪后的源区域绘制到目标区域
                    ctx.drawImage(
                        imgElement,
                        sourceX, sourceY, sourceWidth, sourceHeight,  // 源图片的裁剪区域
                        newX, newY, newImgWidth, newImgHeight         // 目标画布的绘制区域
                    );            
                }

                // 转换为blob并下载        
                offscreenCanvas.toBlob((blob) => {
                    if (!blob) {
                        console.error('blob转换失败');
                        return;
                    }            
                    
                    const url = URL.createObjectURL(blob);
                    const link = document.createElement('a');
                    link.href = url;
                    link.download = `resized_image_${Date.now()}.png`;
                    document.body.appendChild(link);            
                    link.click();
                    document.body.removeChild(link);
                    URL.revokeObjectURL(url);
                                
                }, 'image/png');
                
            } catch (error) {
                console.error('处理图片时出错:', error);
            }
                
        } catch (error) {
            console.error('处理图片时出错:', error);
        }
    };

    // 清除选择框
    const clearSelectionRect = () => {
        setSelectionRects([]);
        setCurrentSelectionRect(null);
        setIsRectSelecting(false);
    };

    // 渲染清除按钮
    const renderClearButton = () => {
        if (!enableProcessing || (brushStrokes.length === 0 && currentStroke.length === 0) || eraseMode !== EDIT_MODES.ERASER) {
            return null;
        }
        
        return (
            <button
                className={styles.clearButton}
                onClick={clearBrushStrokes}
                title="清除所有痕迹"
                style={{
                    position: 'absolute',
                    top: '16PX',
                    right: '16PX',
                    zIndex: 20,
                    padding: '8PX 12PX',
                    backgroundColor: '#ff4d4f',
                    color: 'white',
                    border: 'none',
                    borderRadius: '4PX',
                    cursor: 'pointer',
                    fontSize: '12PX'
                }}
            >
                清除
            </button>
        );
    };

    return (
        <>
            <div 
                {...getMouseHandlers()}
                style={{
                    position: 'absolute',
                    width:"100%",
                    height:'100%',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    pointerEvents: enableProcessing ? 'auto' : 'none',
                    cursor: (() => {
                        // 空格键拖动的光标（优先级最高）
                        if (isSpacePressed && mediaScale > 1) {
                            return isDragging ? 'grabbing' : 'grab';
                        }
                        // DRAG模式的光标
                        if (eraseMode === EDIT_MODES.DRAG) {
                            return 'default';
                        }
                        // 其他工具模式的光标
                        if (enableProcessing && (eraseMode === EDIT_MODES.BRUSH || eraseMode === EDIT_MODES.ERASER)) {
                            return 'none';
                        }
                        if (enableProcessing && eraseMode === EDIT_MODES.POINT) {
                            return 'crosshair';
                        }
                        if (enableProcessing && eraseMode === EDIT_MODES.RECT) {
                            return 'crosshair';
                        }
                        return 'default';
                    })(),
                    zIndex: 10
                }}
            >
                {renderCanvas()}
                {/* {renderResetButton()} */}
                {!hideDisplayCanvas&&renderClearButton()}
                {showEraserPreview&&!hideDisplayCanvas && enableProcessing && eraseMode === EDIT_MODES.ERASER && (
                    <div
                        className={styles.eraserPreview}
                        style={{
                            position: 'absolute',
                            left: mousePosition.x - (toolSize * mediaScale) / 2,
                            top: mousePosition.y - (toolSize * mediaScale) / 2,
                            width: toolSize * mediaScale,
                            height: toolSize * mediaScale,
                            border: '2px solid rgba(255, 255, 255,1)',
                            boxShadow: `inset 0 0 ${toolSize/4*mediaScale}PX ${toolSize/4*mediaScale}PX rgba(255, 255, 255, 0.9)`,
                            borderRadius: '50%',
                            pointerEvents: 'none',
                            zIndex: 15
                        }}
                    />
                )}
                {showBrushPreview &&!hideDisplayCanvas&& enableProcessing && eraseMode === EDIT_MODES.BRUSH && (
                    <div
                        className={styles.brushPreview}
                        style={{
                            position: 'absolute',
                            left: mousePosition.x - (toolSize * mediaScale) / 2,
                            top: mousePosition.y - (toolSize * mediaScale) / 2,
                            width: toolSize * mediaScale,
                            height: toolSize * mediaScale,
                            border: '2px solid rgba(255, 255, 255,1)',
                            boxShadow: `inset 0 0 ${toolSize/4*mediaScale}PX ${toolSize/4*mediaScale}PX rgba(255, 255, 255, 0.9)`,
                            borderRadius: '50%',
                            pointerEvents: 'none',
                            zIndex: 15
                        }}
                    />
                )}

            </div>
            {selectedRatio&&renderbaseMap()}
            {renderResizeHandles}
        </>
    );
});

export default memo(CanvasDrawing);